<template>
  <div>
    <el-dialog v-model="show" :title="id ? $t('编辑个人信息') : $t('添加管理员')" width="643" @close="closePersonDialog">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item :label="$t('头像')" :label-width="formLabelWidth" :label-position="labelPosition" prop="headUrl">
          <el-upload class="user-upload" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false"
                     :auto-upload="true" :on-success="handleUploadSuccess" :on-error="handleUploadError"
                     accept="image/jpeg, image/png, image/gif, image/bmp, image/webp" :before-upload="beforeUpload">
            <img v-if="form.headUrl" :src="form.headUrl" alt="" class="avatar" />
            <div v-else class="avatar-upload"></div>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('姓名')" :label-width="formLabelWidth" :label-position="labelPosition" prop="realName">
          <el-input v-model="form.realName" autocomplete="off" :placeholder="$t('请输入姓名')" />
        </el-form-item>
        <el-form-item :label="$t('邮箱')" :label-width="formLabelWidth" :label-position="labelPosition" prop="email">
          <el-input v-model="form.email" autocomplete="off" :placeholder="$t('请输入邮箱')" />
        </el-form-item>
        <el-form-item :label="$t('手机号')" :label-width="formLabelWidth" :label-position="labelPosition" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off" :placeholder="$t('请输入手机号')" />
        </el-form-item>
        <!-- 添加管理员时显示密码和确认密码框 -->
        <el-form-item v-if="!id" :label="$t('密码')" :label-width="formLabelWidth" :label-position="labelPosition"
                      prop="password">
          <el-input v-model="form.password" type="password" autocomplete="off" :placeholder="$t('请输入密码')" />
        </el-form-item>
        <el-form-item v-if="!id" :label="$t('确认密码')" :label-width="formLabelWidth" :label-position="labelPosition"
                      prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" autocomplete="off" :placeholder="$t('请确认密码')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closePersonDialog">{{ $t('取消') }}</el-button>
          <el-button type="primary" @click="submitForm" class="confirm">
            {{ $t('确认') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
  import { addCompanyUser, editCompanyUserInfo, getCompanyUserInfo } from '@/api/index';

  export default {
    props: {
      id: {
        type: Number,
        default: null
      }
    },
    data() {
      return {
        uploadUrl: `${process.env.VUE_APP_BASE_API}sys/oss/upload`,
        uploadHeaders: {
          Token: `${localStorage.getItem('token')}`,
        },
        show: true,
        formLabelWidth: '110px',
        labelPosition: 'left',
        form: {
          realName: '',
          email: '',
          mobile: '',
          headUrl: '',
          password: '', // 密码
          confirmPassword: '', // 确认密码
        },
        // 校验规则
        rules: {
          headUrl: [
            { required: true, message: this.$t('请上传头像'), trigger: 'blur' },
          ],
          realName: [
            { required: true, message: this.$t('请输入姓名'), trigger: 'blur' },
          ],
          email: [
            { required: true, message: this.$t('请输入邮箱'), trigger: 'blur' },
            { type: 'email', message: this.$t('请输入正确的邮箱格式'), trigger: ['blur', 'change'] },
          ],
          mobile: [
            { required: true, message: this.$t('请输入手机号'), trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: this.$t('请输入正确的手机号格式'), trigger: ['blur', 'change'] },
          ],
          password: [
            { required: true, message: this.$t('请输入密码'), trigger: 'blur' },
            { min: 6, message: this.$t('密码长度至少为6位'), trigger: 'blur' },
          ],
          confirmPassword: [
            { required: true, message: this.$t('请确认密码'), trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (value !== this.form.password) {
                  callback(new Error(this.$t('两次输入的密码不一致')));
                } else {
                  callback();
                }
              },
              trigger: ['blur', 'change'],
            },
          ],
        },
      };
    },
    mounted() {
      this.init();
    },
    methods: {
      beforeUpload() {
        this.loading = ElLoading.service({
          lock: true,
          text: this.$t('Loading'),
          background: 'rgba(0, 0, 0, 0.7)',
        });
      },
      handleUploadSuccess(response, file, fileList) {
        if (this.loading) {
          this.loading.close();
        }
        if (response.code === 0) {
          this.form.headUrl = response.data.src;
          ElMessage({
            type: 'success',
            message: this.$t('文件上传成功!'),
          });
        }
      },
      handleUploadError(err, file, fileList) {
        if (this.loading) {
          this.loading.close();
        }
        ElMessage({
          type: 'error',
          message: this.$t('文件上传失败!'),
        });
      },
      // 初始化表单
      init() {
        if (this.id) {
          this.getUserInfo(); // 获取用户信息
        } else {
          this.resetForm(); // 重置表单
        }
      },
      // 获取用户信息
      async getUserInfo() {
        try {
          const { data } = await getCompanyUserInfo(this.id);
          if (data.code === 0) {
            this.form = data.data; // 填充表单
          }
        } catch (error) {
          console.error(this.$t('获取用户信息失败:'), error);
        }
      },
      // 重置表单
      resetForm() {
        this.form = {
          realName: '',
          email: '',
          mobile: '',
          headUrl: '',
          password: '', // 重置密码字段
          confirmPassword: '', // 重置确认密码字段
        };
      },
      // 提交表单
      async submitForm() {
        let flag = true;
        // 校验表单
        await this.$refs?.formRef?.validate((e) => {
          flag = e;
        });
        if (flag) {
          try {
            let response;
            if (this.id) {
              response = await editCompanyUserInfo(this.id, { ...this.form });
            } else {
              response = await addCompanyUser(this.form);
            }
            if (response.data.code === 0) {
              ElMessage({
                type: 'success',
                message: this.id ? this.$t('编辑成功') : this.$t('添加成功'),
              });
              this.closePersonDialog();
              this.$emit('refresh');
            } else {
              ElMessage({
                type: 'error',
                message: response.data.message || this.$t('操作失败'),
              });
            }
          } catch (error) {
            console.error(this.$t('提交表单失败:'), error);
            ElMessage({
              type: 'error',
              message: this.$t('提交表单失败'),
            });
          }
        }
      },
      closePersonDialog() {
        this.show = false;
        this.$emit('closePersonDialog');
      },
    },
  };
</script>
<style lang="scss">
.user-upload {

  .avatar-upload,
  .avatar {
    width: 107px;
    height: 107px;
    background: #404040;
    border-radius: 50%;
  }
}
</style>
